<?php declare(strict_types=1);

$di = \application\units\Di::getInstance();

$params = [
    'admin_id' => $di->auth->id,
    'id'       => explode(',', (string)$di->request->params('id')),
];

if ($params['admin_id'] !== null) {
    $roleIds = $di->auth->getChildrenRoleIds($params['admin_id'], true);
    if (array_diff($params['id'], $roleIds)) throw new \LogicException('不能删除自己的角色');
}

$row = $di->db->find('select * from admin_role where id in (:id)', [
    'id' => $params['id'],
]);

if (!$row) throw new \LogicException('未找到记录');

$has = $di->db->find('select * from admin_role_access where role_id in (:role_id)', [
    'role_id' => $params['id'],
]);
if ($has) throw new \LogicException('角色组中有管理员不能操作');

try {
    
    $di->db->beginTransaction();
    
    $stat = $di->db->execute('delete from admin_role where id in (:id)', [
        'id' => $params['id'],
    ]);
    
    if ($stat->rowCount() <= 0) throw new PDOException('操作失败');
    
    $stat = $di->db->execute('delete from admin_role_resource_access where role_id in (:role_id)', [
        'role_id' => $params['id'],
    ]);
    
    if ($stat->rowCount() <= 0) throw new PDOException('操作失败');
    
    $di->db->commit();
} catch (\Exception $e) {
    $di->db->rollback();
    throw $e;
}

return [];